//index.js
//获取应用实例
var app = getApp();
var util = require('../../utils/util.js')
const APP_ID = '';//输入小程序appid
const APP_SECRET = '';//输入小程序app_secret
var OPEN_ID = ''//储存获取到openid
var SESSION_KEY = ''//储存获取到session_key
var distance;
var form_id;
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    totalPrice: 0,//商品总金额
    mapkey: '',
    order: [],
    address: '',
    distance: '0',
    form_id: '',
    beizhu: '',
    dnzt: false,
    qlq: true,
    sdindex: 0,
    qzf: true,
    showModal: false,
    zftype: true,
    zfz: false,
    typeList: [//产品分类
    ],
    xzggindex: '0',
    showModal: false,
    boxfre: true,
    changeHidden1: true,
    changeHidden: true,
    toastHidden: true,
    selected1: true,
    selected2: false,
    selected3: false,
    showview: true,
    hidden1: false,
    hidden2: true,
    hidden3: true,
    // 商家部分开始
    catalogSelect: 0,
    store: [],
    http: [],
    showView: false,
    close: false,
    login: [],
    rest: '',
    start_at: '',
    conditions: '',
    preferential: '',
    dishes: [],
    link: '',
    toView: '0',
    store_name: '',//餐厅名字
    scrollTop: 100,
    totalPrice: 0,// 总价格
    totalCount: 0, // 总商品数
    carArray: [],
    freight: 0,//配送费
    payDesc: 0,
    userInfo: {},
    parentIndex: 0,
    url: '',
    //商家部分结束
    // 切换部分的数据
    hidden: false,
    curNav: 1,
    curIndex: 0,
    cart: [],
    cartTotal: 0,
    one: 1,
    ping: '',
    hdnum: 0,
    showFoodList: [],
    star1: [
      { url: '../images/full-star.png' },
      { url: '../images/no-star.png' },
      { url: '../images/no-star.png' },
      { url: '../images/no-star.png' },
      { url: '../images/no-star.png' }
    ],
    star2: [
      { url: '../images/full-star.png' },
      { url: '../images/full-star.png' },
      { url: '../images/no-star.png' },
      { url: '../images/no-star.png' },
      { url: '../images/no-star.png' }
    ],
    star3: [
      { url: '../images/full-star.png' },
      { url: '../images/full-star.png' },
      { url: '../images/full-star.png' },
      { url: '../images/no-star.png' },
      { url: '../images/no-star.png' }
    ],
    star4: [
      { url: '../images/full-star.png' },
      { url: '../images/full-star.png' },
      { url: '../images/full-star.png' },
      { url: '../images/full-star.png' },
      { url: '../images/no-star.png' }
    ],
    star5: [
      { url: '../images/full-star.png' },
      { url: '../images/full-star.png' },
      { url: '../images/full-star.png' },
      { url: '../images/full-star.png' },
      { url: '../images/full-star.png' }
    ],
    til: [
      { 'foodname': '热销' },
      { 'foodname': '折扣' },
      { 'foodname': '热卖产品' },
      { 'foodname': '超值套餐' },
      { 'foodname': '湘菜' },
      { 'foodname': '粤菜' },
      { 'foodname': '淮菜' },
      { 'foodname': '鲁菜' },
      { 'foodname': '东北菜' },
    ],
    // 自带弹框
    // text:"这是一个页面"
    hiddenModal: true,
    hide: true,
    // 灰色显示
    cartgray: true,
    // 正常显示
    cart: true,
    foodList: [],
    winHeight: "",//窗口高度
    currentTab: 0, //预设当前项的值
    scrollLeft: 0, //tab标题的滚动条位置
    address: [],
    coupons_id: '',
    pre: 0,
  },
  urls: function () {
    wx.navigateTo({
      url: '/zh_dianc/pages/addresslist/addresslist',
    })
  },
  yurls: function () {
    wx.navigateTo({
      url: '/zh_dianc/pages/coupons/mine_coupons?totalPrice=' + this.data.totalPrice + '&state=1',
    })
  },
  useAddress: function (user_id) {
    var that = this;
    app.util.request({
      'url': 'entry/wxapp/UseAddress',
      'cachetime': '0',
      data: { user_id: user_id },
      success: function (res) {
        console.log(res)
        if (res.data.code == 200) {
          that.setData({
            address: res.data.data
            // address:""
          })
        } else {
          that.setData({
            address: false
          })
        }
      }
    })
  },
  ycgg: function () {
    this.setData({
      showModal: false,
    })
  },
  searchValueInput: function (e) {
    let key = e.detail.value;
    // !!key && app.getSearchRes(key, getApp().sjid);

    // 菜品信息
    var that = this
    var dishes_type = that.data.types
    console.log(dishes_type)
    app.util.request({
      'url': 'entry/wxapp/Dishes',
      'cachetime': '0',
      data: { id: getApp().sjid, dishes_type: dishes_type, name: key },
      success: function (res) {
        for (var i = 0; i < res.data.length; i++) {
          for (var j = 0; j < res.data[i].goods.length; j++) {
            res.data[i].goods[j].xs_num = Number(res.data[i].goods[j].xs_num)
            res.data[i].goods[j].sit_ys_num = Number(res.data[i].goods[j].sit_ys_num)
          }
        }
        console.log(res.data)
        console.log('----------------------------商品分类-------------------------')
        that.setData({
          dishes: res.data
        })
      },
    })

  },
  // 弹框
  listenerButton: function () {
    var that = this;
    var user_id = wx.getStorageSync('users').id
    that.useAddress(user_id);
    this.setData({
      hiddenModal: !this.data.hiddenModal,
      hide: !this.data.hide,
    })
  },

  listenerConfirm: function () {
    this.setData({
      hiddenModal: true,
      hide: false,
    })
  },

  listenerCancel: function () {
    this.setData({
      hiddenModal: true,
      hide: true,
    })
  },
  // 滚动切换标签样式
  switchTab: function (e) {
    this.setData({
      currentTab: e.detail.current
    });
    this.checkCor();
    this.setShowFoodList();
  },

  // 点击标题切换当前页时改变样式
  swichNav: function (e) {
    var cur = e.target.dataset.current;
    if (this.data.currentTaB == cur) { return false; }
    else {
      this.setShowFoodList();
      this.setData({
        currentTab: cur
      })
    }
  },
  //判断当前滚动超过一屏时，设置tab标题滚动条。
  checkCor: function () {
    if (this.data.currentTab > 4) {
      this.setData({
        scrollLeft: 300
      })
    } else {
      this.setData({
        scrollLeft: 0
      })
    }
  },
  setShowFoodList: function () {
    let currentTab = this.data.currentTab,
      foodList = this.data.foodList;
    //应为分类的排序和所有菜品foodList的前后顺序不同所以需要根据分类id展示而不是 currentTab
    // let showFoodList = foodList[currentTab].goods;  
    let foodListIndex = this.getCurrentTabId(currentTab);
    for (let key in foodList) {
      if (foodListIndex == foodList[key].id) {
        this.setData({ "showFoodList": foodList[key].goods });
        break;
      }
    }
  },
  //获取商品集合（列表）
  getFoodList: function (store_id) {
    let that = this;

    app.util.request({
      'url': 'entry/wxapp/AppDishes',
      'cachetime': '0',
      'data': { "store_id": store_id },
      success: function (res) {
        console.log(res);
        console.log('-----------------------------------------------------------------------------')
        that.setData({
          "foodList": res.data
        });
        that.setShowFoodList();
      },
    })
  },
  //获取商品分类 
  getTypeList: function (store_id) {
    let that = this;
    app.util.request({
      'url': 'entry/wxapp/AppDishesType',
      'cachetime': '0',
      'data': { "store_id": store_id },
      success: function (res) {
        that.setData({
          "typeList": res.data
        })
      },
    })
  },
  changeData: function (coupons_id, preferential) {
    var that = this
    if (preferential == null) {
      var pre = 0
    } else {
      var pre = Number(preferential)
    }
    var users = wx.getStorageSync('users')
    var new_user = wx.getStorageSync('new_user')
    console.log(parseFloat(this.data.totalPrice));
    that.setData({
      coupons_id: coupons_id,
      pre: pre,
      totalPrice: parseFloat(this.data.totalPrice) - parseFloat(pre),
      new_user: new_user,
      users: users,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var users = wx.getStorageSync('users')
    var new_user = wx.getStorageSync('new_user')
    that.setData({
      new_user: new_user,
      users: users,
    })

    var that = this;
    var new_user = wx.getStorageSync('new_user')
    var pre = 0
    // 商家信息
    app.util.request({
      'url': 'entry/wxapp/Store',
      'cachetime': '0',
      data: { id: getApp().sjid },
      success: function (res) {
        console.log(res)
        console.log(res.data.coordinates.split(','))
        var loc = res.data.coordinates.split(',')
        //设置导航栏背景色
        wx.setNavigationBarColor({
          frontColor: '#000000',
          backgroundColor: "#ffffff",
        })
        that.setData({
          color: res.data.color,
          sd_time: res.data.sd_time
        })
        //满减
        app.util.request({
          'url': 'entry/wxapp/Reduction',
          'cachetime': '0',
          data: { id: getApp().sjid },
          success: function (res1) {
            console.log(res1)
            var wmmj = [];
            for (let i = 0; i < res1.data.length; i++) {
              if (res1.data[i].type == '1' || res1.data[i].type == '3') {
                wmmj.push(res1.data[i])
              }
            }
            console.log(wmmj)
            // 配送费
            var fre = Number(res.data.freight)
            // 满减的优惠条件数组
            if (wmmj.length == 0) {
              var con = [{ 'full': '1000000' }]
            }
            else {
              var con = wmmj
            }
            // 满减的条件的索引
            var conindex = con.length - 1
            // 满减的优惠金额
            var cut
            // 获取从上一个页面保存的数据
            var order = wx.getStorageSync('order')
            console.log(order)
            // 计算订单的总金额
            var totalPrice = 0;
            // 餐盒费
            var totalbox = 0;
            for (var i = 0; i < order.length; i++) {
              totalPrice += order[i].money * order[i].num + order[i].box_fee * order[i].num;
              totalbox += order[i].box_fee * order[i].num;
            }
            console.log(totalPrice, con)
            // 配送费
            var freight = Number(res.data.freight)
            console.log('配送费为' + freight)
            if (freight > 0) {
              var freight = Number(res.data.freight)
            } else {
              var freight = 0
            }
            // 用户的身份

            // 判断商家是否开启新用户立减优惠
            var xyh_open = Number(res.data.xyh_open)
            // 下单立减优惠金额
            var xyh_money = Number(res.data.xyh_money)
            if (xyh_open == 1) {
              // 商家开启了新用户下单立减  需要根据用户身份去计算用户的支付金额
              if (new_user == 1) {
                console.log('这是一个新用户')
                var money = totalPrice - xyh_money + freight
                if (money <= 0) {
                  money = 0.01
                }
                console.log('商家开启了下单立减优惠，而且用户是一个新用户，不享受满减活动以及优惠券，支付的金额为' + money)
              } else {
                // 订单总金额大于满减金额
                if (Number(totalPrice) >= Number(con[con.length - 1].full)) {
                  console.log(that.jsmj(totalPrice, con))
                  conindex = that.jsmj(totalPrice, con)
                  cut = Number(con[conindex].reduction)
                  console.log(cut)
                  // 用户没有选择优惠券
                  if (pre == 0) {
                    var money = totalPrice + freight - cut
                    console.log('商家开启了下单立减优惠，而且用户是一老用户，没有使用优惠券，支付的金额为' + money)
                  }
                  else {
                    if (totalPrice + freight - cut - pre <= 0) {
                      var money = 0.01
                      console.log('商家开启了下单立减优惠，而且用户是一老用户，使用了优惠券并且优惠超出总价，支付的金额为' + money)
                    }
                    else {
                      var money = totalPrice + freight - cut - pre
                      console.log('商家开启了下单立减优惠，而且用户是一老用户，使用了优惠券并且总价大于优惠，支付的金额为' + money)
                    }
                  }
                }
                else {
                  if (pre == 0) {
                    var money = totalPrice + freight
                  }
                  else {
                    // 判断总支付金额是否小于等于0
                    if (totalPrice + freight - pre <= 0) {
                      var money = 0.01
                    }
                    else {
                      var money = totalPrice + freight - pre
                    }
                  }
                  console.log('用户是一个老用户，不享受新用户下单立减活动，订单的金额小于满减的金额' + money, con)
                }
              }
            } else {
              // 商家没有开启新用户下单立减   不显示用户身份  也不计算价格
              if (Number(totalPrice) >= Number(con[con.length - 1].full)) {
                console.log(that.jsmj(totalPrice, con))
                conindex = that.jsmj(totalPrice, con)
                cut = Number(con[conindex].reduction)
                console.log(cut)
                if (pre == 0) {
                  var money = totalPrice + freight - cut
                }
                else {
                  // 判断总支付金额是否小于等于0
                  if (totalPrice + freight - cut - pre <= 0) {
                    var money = 0.01
                  }
                  else {
                    var money = totalPrice + freight - cut - pre
                  }
                }
                console.log('商家没有开启新用户立减，而且用户是一个老用户，订单的金额大于满减的金额，用户支付的金额为' + money)
              } else {
                if (pre == 0) {
                  var money = totalPrice + freight
                }
                else {
                  // 判断总支付金额是否小于等于0
                  if (totalPrice + freight - pre <= 0) {
                    var money = 0.01
                  }
                  else {
                    var money = totalPrice + freight - pre
                  }
                }
                console.log('商家没有开启开启新用户立减，而且用户是一个老用户，订单的金额小于满减的金额，用户支付的金额为' + money, con)
              }
            }
            that.setData({
              xyh_open: xyh_open,
              xyh_money: xyh_money,
              store: res.data,
              money: money.toFixed(2),
              money1: money.toFixed(2),
              totalPrice: totalPrice,
              totalbox: totalbox,
              freight: freight,
              fre: fre,
              order: order,
              con: con,
              yh: Number(con[conindex].full),
              cut: cut,
              seller_id: res.data.id
            })
            console.log(that.data)
          }
        })
        distance = Number(res.data.distance) * 1000

        qqmapsdk.reverseGeocoder({
          location: {
            latitude: loc[0],
            longitude: loc[1]
          },
          coord_type: 3,
          success: function (res) {
            console.log(res);
            console.log('坐标转地址后的经纬度起点：', res.result.ad_info.location)
            that.setData({
              start: res.result.ad_info.location,
              qzf: false,
            })
          },
          fail: function (res) {
            console.log(res);
          },
          complete: function (res) {
            console.log(res);
          }
        });
      },
    })
    // 获取用户poenid
    var openid = wx.getStorageSync('openid')
    console.log(openid)
    // 获取用户user_id
    var user_id = wx.getStorageSync('users').id
    that.setData({
      openid: openid,
      user_id: user_id
    })

    // that.toPay();

    this.getTypeList(getApp().sjid);
    this.getFoodList(getApp().sjid);

    // this.setShowFoodList();
    wx.getStorage({
      key: 'imglink',
      success: function (res) {
        that.setData({ "imgLink": res.data });
      }
    })
    var that = this;
    //  高度自适应
    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR - 180;
        console.log(calc)
        that.setData({
          winHeight: calc
        });
      }
    });
    //登录
    wx.getUserInfo({
      success: function (res) {
        console.log(res.userInfo)
        var userInfo = res.userInfo;
        that.setData({
          nickName: userInfo.nickName,
          avatarUrl: userInfo.avatarUrl,
        })
      }, fail: function () {
        wx.showModal({
          title: '警告',
          content: '您点击了拒绝授权,无法正常显示个人信息,点击确定重新获取授权。',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.openSetting({
                success: (res) => {
                  if (res.authSetting["scope.userInfo"]) {////如果用户重新同意了授权登录
                    wx.getUserInfo({
                      success: function (res) {
                        console.log(res.userInfo)
                        var userInfo = res.userInfo;
                        that.setData({
                          nickName: userInfo.nickName,
                          avatarUrl: userInfo.avatarUrl,
                        })
                      }
                    })
                  } else {
                    that.setData({
                      nickName: '',
                      avatarUrl: '',
                    })
                  }
                },
                fail: function (res) {
                }
              })
            }
          }
        })
      }, complete: function (res) {
      }
    })
    // 获取用户登录信息
    wx.login({
      success: function (res) {
        var code = res.code
        wx.setStorageSync("code", res.code)
        app.util.request({
          'url': 'entry/wxapp/openid',
          'cachetime': '0',
          data: { code: code },
          success: function (res) {
            console.log(res)
            wx.setStorageSync("key", res.data.session_key)
            // var img = that.data.userInfo.avatarUrl
            // var name = that.data.userInfo.nickName
            // 异步保存用户openid
            wx.setStorageSync("openid", res.data.openid)
            var openid = res.data.openid
            console.log(openid)
            // 获取用户登录信息
            if (openid == '') {
              wx: wx.showToast({
                title: '没有获取到openid',
                icon: '',
                image: '',
                duration: 1000,
                mask: true,
                success: function (res) { },
                fail: function (res) { },
                complete: function (res) { },
              })
            } else {
              app.util.request({
                'url': 'entry/wxapp/Login',
                'cachetime': '0',
                data: { openid: openid, img: that.data.avatarUrl, name: that.data.nickName },
                success: function (res) {
                  console.log(res)
                  // 异步保存用户登录信息
                  wx.setStorageSync('users', res.data)
                  // 获取用户状态
                  app.util.request({
                    'url': 'entry/wxapp/New',
                    'cachetime': '0',
                    data: { user_id: res.data.id, store_id: getApp().sjid },
                    success: function (res) {
                      console.log(res)
                      wx.setStorageSync('new_user', res.data)
                    },
                  })
                },
              })
            }

          },
        })
      }
    })
    //
    console.log(options)
    var that = this
    var types = Number(options.type)
    if (types == 1) {
      console.log('用户选择的是店内点餐')
    } else {
      console.log('用户选择的是外卖点餐')
    }
    that.setData({
      types: types
    })
    // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
    var scene = decodeURIComponent(options.scene).split(',')
    console.log(scene)
    if (scene != 'undefined') {
      getApp().sjid = scene[1]
      this.setData({
        types: 1,
        tableid: scene[0]
      })
      app.util.request({
        'url': 'entry/wxapp/Store',
        'cachetime': '0',
        data: { id: getApp().sjid },
        success: function (res) {
          console.log(res)
          var loc = res.data.coordinates.split(',')
          qqmapsdk = new QQMapWX({
            key: "K3HBZ-4QRC3-2RC3U-YOLYP-GJFA2-JNFST"
          });
          qqmapsdk.reverseGeocoder({
            location: {
              latitude: loc[0],
              longitude: loc[1]
            },
            coord_type: 3,
            success: function (res) {
              console.log(res);
              console.log('坐标转地址后的经纬度起点：', res.result.ad_info.location)
              that.setData({
                start: res.result.ad_info.location,
                qzf: false,
              })
            },
            fail: function (res) {
              console.log(res);
            },
            complete: function (res) {
              console.log(res);
            }
          });
          if (res.data.is_czztpd == '1') {
            // 获取桌子信息
            app.util.request({
              'url': 'entry/wxapp/Zhuohao',
              'cachetime': '0',
              data: { id: scene[0] },
              success: function (res) {
                console.log(res)
                if (res.data.status == '0') {
                  wx.showModal({
                    title: '提示',
                    content: '桌位信息：' + res.data.type_name + '--' + res.data.table_name,
                    showCancel: false,
                    success: function (res) { },
                    fail: function (res) { },
                    complete: function (res) { },
                  })
                  that.setData({
                    kt: false,
                  })
                }
                else {
                  wx.showModal({
                    title: '提示',
                    content: '此桌已开台暂不能点餐,请选择其他座位',
                    showCancel: false,
                    success: function (res) { },
                    fail: function (res) { },
                    complete: function (res) { },
                  })
                  setTimeout(function () {
                    wx.navigateBack({

                    })
                  }, 1000)
                  that.setData({
                    kt: true,
                  })
                }
              },
            })
          }
          else {
            // 获取桌子信息
            app.util.request({
              'url': 'entry/wxapp/Zhuohao',
              'cachetime': '0',
              data: { id: scene[0] },
              success: function (res) {
                console.log(res)
                wx.showModal({
                  title: '提示',
                  content: '桌位信息：' + res.data.type_name + '--' + res.data.table_name,
                  showCancel: false,
                  success: function (res) { },
                  fail: function (res) { },
                  complete: function (res) { },
                })
                that.setData({
                  kt: false,
                })
              },
            })
          }
        },
      })
      // wx.setStorageSync('tableid', scene)
    }
    showview: (options.showview == "true" ? true : false)
    showView: (options.showView == "true" ? true : false)
    that.reload()
  },
  plusNumEvent: function (e) {
    let curGoodId = e.currentTarget.id,
      showFoodList = this.data.showFoodList,
      num, obj;
    for (let key in showFoodList) {
      if (curGoodId == showFoodList[key].id) {
        obj = showFoodList[key];
        if (!!showFoodList[key].choseNum) {
          num = showFoodList[key].choseNum + 1;
        } else {
          num = 1;
        }
        obj["choseNum"] = num;
        showFoodList[key] = obj;
        app.changeChosedFood(curGoodId, obj);
        break;
      }
    }
    this.setData({ "showFoodList": showFoodList });
  },
  getCurrentTabId: function (currentTab) {
    // this.getTypeList();

    let typeList = this.data.typeList;
    console.log(typeList);
    console.log('----------------------------分类列表----------------------')
    // if (typeList[currentTab]){
    return typeList[currentTab].id;



  },
  reduceNumEvent: function (e) {
    let curGoodId = e.currentTarget.id,
      showFoodList = this.data.showFoodList,
      num, obj;
    for (let key in showFoodList) {
      if (curGoodId == showFoodList[key].id) {
        obj = showFoodList[key];
        if (!!showFoodList[key].choseNum) {
          num = showFoodList[key].choseNum - 1;
        } else {
          num = 0;
        }
        obj["choseNum"] = num <= 0 ? 0 : num;
        showFoodList[key] = obj;
        app.changeChosedFood(curGoodId, obj);
        break;
      }
    }
    this.setData({ "showFoodList": showFoodList });
  },
  reload: function (e) {
    var that = this
    // 获取用户点击的状态是店内点餐还是外卖
    var time = util.formatTime(new Date());
    var current_time = time.slice(11, 16)
    var key = this.data.store_name
    wx.showShareMenu({
      withShareTicket: true
    })

    // 接口数据

    // 商家信息
    app.util.request({
      'url': 'entry/wxapp/Store',
      'cachetime': '0',
      data: { id: getApp().sjid },
      success: function (res) {
        var loc = res.data.coordinates.split(',')
        qqmapsdk = new QQMapWX({
          key: "K3HBZ-4QRC3-2RC3U-YOLYP-GJFA2-JNFST"
        });
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: loc[0],
            longitude: loc[1]
          },
          coord_type: 3,
          success: function (res) {
            console.log(res);
            console.log('坐标转地址后的经纬度起点：', res.result.ad_info.location)
            that.setData({
              start: res.result.ad_info.location,
              qzf: false,
            })
          },
          fail: function (res) {
            console.log(res);
          },
          complete: function (res) {
            console.log(res);
          }
        });
        if (res.data.wm_name != '' && that.data.types == 2) {
          wx.setNavigationBarTitle({
            title: res.data.wm_name,
          })
        }
        if (res.data.dn_name != '' && that.data.types == 1) {
          wx.setNavigationBarTitle({
            title: res.data.dn_name,
          })
        }
        //设置导航栏背景色
        wx.setNavigationBarColor({
          frontColor: '#000000',
          backgroundColor: "#ffffff",
        })
        //商家地址
        app.util.request({
          'url': 'entry/wxapp/zhuanh',
          'cachetime': '0',
          data: { op: res.data.coordinates },
          success: function (res) {
            console.log(res)
            console.log(res.data.locations[0].lat + ',' + res.data.locations[0].lng)
            that.setData({
              sjdzlat: res.data.locations[0].lat,
              sjdzlng: res.data.locations[0].lng
            })
          }
        })
        console.log(res)
        //满减
        app.util.request({
          'url': 'entry/wxapp/Reduction',
          'cachetime': '0',
          data: { id: getApp().sjid },
          success: function (res1) {
            console.log(res1)
            var tnmj = [], wmmj = [];
            for (let i = 0; i < res1.data.length; i++) {
              if (res1.data[i].type == '2' || res1.data[i].type == '3') {
                tnmj.push(res1.data[i])
              }
              if (res1.data[i].type == '1' || res1.data[i].type == '3') {
                wmmj.push(res1.data[i])
              }
            }
            if (that.data.types == 1) {
              var mj = tnmj
              that.setData({
                mj: tnmj
              })
            }
            if (that.data.types == 2) {
              var mj = wmmj
              that.setData({
                mj: wmmj
              })
            }
            if (mj.length != 0 && res.data.xyh_open == '1') {
              that.setData({
                hdnum: 2
              })
            }
            else if ((mj.length != 0 && res.data.xyh_open != '1') || (mj.length == 0 && res.data.xyh_open == '1')) {
              that.setData({
                hdnum: 1
              })
            }
            else {
              that.setData({
                hdnum: 0
              })
            }
          }
        })
        var seller_id = res.data.id
        var shop_time = res.data.time
        var close_time = res.data.time2
        var shop_time1 = res.data.time3
        var close_time1 = res.data.time4
        var rest = res.data.is_rest
        console.log('当前的系统时间为' + current_time)
        console.log('商家的营业时间从' + shop_time + '至' + close_time, shop_time1 + '至' + close_time1)

        if (rest == 1) {
          console.log('商家正在休息' + rest)
        } else {
          console.log('商家正在营业' + rest)
        }
        if (close_time1 > shop_time) {
          if (current_time > shop_time && current_time < close_time || current_time > shop_time1 && current_time < close_time1) {
            console.log('商家正常营业')
            that.setData({
              time: 1
            })
          }
          else if (current_time < shop_time || current_time > close_time && current_time < shop_time1) {
            console.log('商家还没开店呐，稍等一会儿可以吗？')
            that.setData({
              time: 2
            })
          }
          else if (current_time > close_time1) {
            console.log('商家以及关店啦，明天再来吧')
            that.setData({
              time: 3
            })
          }
        }
        else if (close_time1 < shop_time) {
          if (current_time > shop_time && current_time < close_time || current_time > shop_time1 && current_time > close_time1 || current_time < shop_time1 && current_time < close_time1) {
            console.log('商家正常营业')
            that.setData({
              time: 1
            })
          }
          else if (current_time < shop_time || current_time > close_time && current_time < shop_time1) {
            console.log('商家还没开店呐，稍等一会儿可以吗？')
            that.setData({
              time: 2
            })
          }
          else if (current_time > close_time1) {
            console.log('商家以及关店啦，明天再来吧')
            that.setData({
              time: 3
            })
          }
        }
        console.log("商家的id为" + seller_id)

        //评分接口
        app.util.request({
          'url': 'entry/wxapp/Score',
          'cachetime': '0',
          data: { seller_id: seller_id },
          success: function (res) {
            console.log(res)
            var score = res.data
            score = score.toFixed(1)
            console.log(score)
            that.setData({
              score: score
            })
          },
        })

        // 评论的接口
        app.util.request({
          'url': 'entry/wxapp/StorePl',
          headers: {
            'Content-Type': 'application/json',
          },
          'cachetime': '0',
          data: { id: seller_id },
          success: function (res) {
            var loc = res.data.coordinates.split(',')
            qqmapsdk = new QQMapWX({
              key: "K3HBZ-4QRC3-2RC3U-YOLYP-GJFA2-JNFST"
            });
            qqmapsdk.reverseGeocoder({
              location: {
                latitude: loc[0],
                longitude: loc[1]
              },
              coord_type: 3,
              success: function (res) {
                console.log(res);
                console.log('坐标转地址后的经纬度起点：', res.result.ad_info.location)
                that.setData({
                  start: res.result.ad_info.location,
                  qzf: false,
                })
              },
              fail: function (res) {
                console.log(res);
              },
              complete: function (res) {
                console.log(res);
              }
            });
            console.log(res.data)
            var length = res.data.length
            console.log(length)
            for (var i = 0; i < res.data.length; i++) {
              res.data[i].score = res.data[i].score.slice(0, 2)
            }
            console.log(res.data)
            that.setData({
              ping: res.data
            })
          },
        })
        that.setData({
          store: res.data,
          rest: rest,
          color: res.data.color,
          seller_id: seller_id,
          start_at: res.data.start_at
        })
      },
    })

    // 网址信息
    app.util.request({
      'url': 'entry/wxapp/Url',
      'cachetime': '0',
      success: function (res) {
        // console.log(res.data)
        that.setData({
          url: res.data
        })
      },
    })

    // 菜品信息
    var that = this
    var dishes_type = that.data.types
    console.log(dishes_type)
    app.util.request({
      'url': 'entry/wxapp/Dishes',
      'cachetime': '0',
      data: { id: getApp().sjid, dishes_type: dishes_type },
      success: function (res) {
        for (var i = 0; i < res.data.length; i++) {
          for (var j = 0; j < res.data[i].goods.length; j++) {
            res.data[i].goods[j].xs_num = Number(res.data[i].goods[j].xs_num)
            res.data[i].goods[j].sit_ys_num = Number(res.data[i].goods[j].sit_ys_num)
          }
        }
        console.log(res.data)
        console.log('----------------------------商品分类-------------------------')
        that.setData({
          dishes: res.data
        })
      },
    })
  },
  // ————————————点击事件开始——————————

  // 点击切换商品
  selected1: function (e) {
    this.setData({
      selected2: false,
      selected3: false,
      selected1: true,
      hidden1: false,
      hidden2: true,
      hidden3: true
    })
  },
  // 点击切换到评价
  selected2: function (e) {
    this.setData({
      selected1: false,
      selected2: true,
      selected3: false,
      hidden1: true,
      hidden2: false,
      hidden3: true
    })
  },
  // 点击切换到评价
  selected3: function (e) {
    this.setData({
      selected1: false,
      selected2: false,
      selected3: true,
      hidden1: true,
      hidden2: true,
      hidden3: false
    })
  },

  // ————————————点击事件结束——————————

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    if (this.data.types == 1) {
      wx.setNavigationBarTitle({
        title: '堂内点餐'
      })
    } else if (this.data.types == 2) {
      wx.setNavigationBarTitle({
        title: '外卖点餐'
      })
    }

    console.log(this.data.types)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this
    // pageNum = 1;
    that.reload()
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // 点击拨打电话
  call_phone: function () {
    var that = this
    wx.makePhoneCall({
      phoneNumber: that.data.store.tel
    })
  },
  // ——————————————点击跳转地图页面——————————
  tomap: function (e) {
    var that = this
    wx.openLocation({
      latitude: that.data.sjdzlat,
      longitude: that.data.sjdzlng,
      name: that.data.store.name,
      address: that.data.store.address
    })
  },
  tzsjhj: function (e) {
    console.log(e.currentTarget.dataset.sjid)
    wx.navigateTo({
      url: '../info/sjhj',
    })
  },
  selectMenu: function (e) {
    var index = e.currentTarget.dataset.itemIndex;
    this.setData({
      toView: 'order' + index.toString(),
      catalogSelect: e.currentTarget.dataset.itemIndex
    })
    console.log('order' + index.toString())

  },
  // 商家打烊
  close: function () {
    // wx.showToast({
    //   title: '商家已经打烊',
    //   icon: 'success',
    //   duration: 2000
    // })
    var that = this;
    that.setData({
      showView: (!that.data.showView)
    })
  },
  zwkc: function () {
    wx.showToast({
      title: '没有库存了',
    })
  },
  // 
  addShopCart: function (e) {
    var that = this;
    console.log(this.data.dishes)
    console.log(this.data.carArray)
    console.log(e.currentTarget.dataset)
    var index = e.currentTarget.dataset.itemIndex;
    var parentIndex = e.currentTarget.dataset.parentindex;
    var gwcindex = e.currentTarget.dataset.gwcindex
    var ggindex = e.currentTarget.dataset.ggindex
    if (ggindex != null) {
      this.data.dishes[parentIndex].goods[index].one++;//菜品里的数字加
      this.data.dishes[parentIndex].goods[index].gg[ggindex].num++;
      var mark = 'a' + index + 'b' + parentIndex + 'c' + this.data.dishes[parentIndex].goods[index].gg[ggindex].id
      if (this.data.types == 2) {
        var money = this.data.dishes[parentIndex].goods[index].gg[ggindex].cost;
      } else {
        var money = this.data.dishes[parentIndex].goods[index].gg[ggindex].cost;
      }
      var box_fee = this.data.dishes[parentIndex].goods[index].box_fee;
      console.log("餐盒费是：" + box_fee)
      var kc = Number(that.data.dishes[parentIndex].goods[index].num);
      var num = this.data.dishes[parentIndex].goods[index].gg[ggindex].num;
      var name = this.data.dishes[parentIndex].goods[index].name + this.data.dishes[parentIndex].goods[index].gg[ggindex].name;
      var id = this.data.dishes[parentIndex].goods[index].id;
      // console.log(id)
      var icon = this.data.dishes[parentIndex].goods[index].img;
      var store = this.data.store
      var obj = { ggindex: ggindex, money: money, num: num, kc: kc, id: id, mark: mark, name: name, index: index, parentIndex: parentIndex, icon: icon, store: store, box_fee: box_fee, allmoney: (money * num).toFixed(2) };
      var carArray1 = this.data.carArray.filter(item => item.mark != mark)
      carArray1.splice(index, 0, obj)
      console.log(carArray1)
      this.setData({
        shop_cart: carArray1,
        carArray: carArray1,
        dishes: this.data.dishes
      })
      wx.setStorageSync("carArr", carArray1)
      console.log(this.data.carArray)
      this.calTotalPrice();
      this.setData({
        payDesc: this.payDesc()
      })
    }
    else {
      console.log(ggindex)
      that.data.dishes[parentIndex].goods[index].one++;
      var mark = 'a' + index + 'b' + parentIndex
      if (that.data.types == 2) {
        var money = that.data.dishes[parentIndex].goods[index].wm_money;
      } else {
        var money = that.data.dishes[parentIndex].goods[index].money;
      }
      var box_fee = that.data.dishes[parentIndex].goods[index].box_fee;
      console.log("餐盒费是：" + box_fee)
      var kc = Number(that.data.dishes[parentIndex].goods[index].num);
      var num = that.data.dishes[parentIndex].goods[index].one;
      var name = that.data.dishes[parentIndex].goods[index].name;
      var id = that.data.dishes[parentIndex].goods[index].id;
      // console.log(id)
      var icon = that.data.dishes[parentIndex].goods[index].img;
      var store = that.data.store
      var obj = { money: money, num: num, kc: kc, id: id, mark: mark, name: name, index: index, parentIndex: parentIndex, icon: icon, store: store, box_fee: box_fee, allmoney: (money * num).toFixed(2) };
      var carArray1 = that.data.carArray.filter(item => item.mark != mark)
      carArray1.splice(index, 0, obj)
      console.log(carArray1)
      that.setData({
        shop_cart: carArray1,
        carArray: carArray1,
        dishes: that.data.dishes
      })
      wx.setStorageSync("carArr", carArray1);
      console.log(that.data.dishes)
      that.calTotalPrice();
      that.setData({
        payDesc: that.payDesc()
      })
    }
  },
  // 
  decreaseShopCart: function (e) {
    var that = this;
    console.log(this.data.dishes)
    console.log(this.data.carArray)
    console.log(e.currentTarget.dataset)
    var index = e.currentTarget.dataset.itemIndex;
    var parentIndex = e.currentTarget.dataset.parentindex;
    var gwcindex = e.currentTarget.dataset.gwcindex
    var ggindex = e.currentTarget.dataset.ggindex
    if (ggindex != null) {
      this.data.dishes[parentIndex].goods[index].one--;//菜品里的数字减
      this.data.dishes[parentIndex].goods[index].gg[ggindex].num--;
      var mark = 'a' + index + 'b' + parentIndex + 'c' + this.data.dishes[parentIndex].goods[index].gg[ggindex].id
      if (this.data.types == 2) {
        var money = this.data.dishes[parentIndex].goods[index].gg[ggindex].cost;
      } else {
        var money = this.data.dishes[parentIndex].goods[index].gg[ggindex].cost;
      }
      var box_fee = this.data.dishes[parentIndex].goods[index].box_fee;
      console.log("餐盒费是：" + box_fee)
      var kc = Number(that.data.dishes[parentIndex].goods[index].num);
      var num = this.data.dishes[parentIndex].goods[index].gg[ggindex].num;
      var name = this.data.dishes[parentIndex].goods[index].name + this.data.dishes[parentIndex].goods[index].gg[ggindex].name;
      var id = this.data.dishes[parentIndex].goods[index].id;
      // console.log(id)
      var icon = this.data.dishes[parentIndex].goods[index].img;
      var store = this.data.store
      var obj = { ggindex: ggindex, money: money, num: num, kc: kc, id: id, mark: mark, name: name, index: index, parentIndex: parentIndex, icon: icon, store: store, box_fee: box_fee, allmoney: (money * num).toFixed(2) };
      var carArray1 = this.data.carArray.filter(item => item.mark != mark)
      carArray1.splice(index, 0, obj)
      console.log(carArray1)
      this.setData({
        shop_cart: carArray1,
        carArray: carArray1,
        dishes: this.data.dishes
      })
      console.log(this.data.carArray)
      this.calTotalPrice();
      this.setData({
        payDesc: this.payDesc()
      })
    }
    else {
      console.log(ggindex)
      that.data.dishes[parentIndex].goods[index].one--;
      var mark = 'a' + index + 'b' + parentIndex
      if (that.data.types == 2) {
        var money = that.data.dishes[parentIndex].goods[index].wm_money;
      } else {
        var money = that.data.dishes[parentIndex].goods[index].money;
      }
      var box_fee = that.data.dishes[parentIndex].goods[index].box_fee;
      console.log("餐盒费是：" + box_fee)
      var kc = Number(that.data.dishes[parentIndex].goods[index].num);
      var num = that.data.dishes[parentIndex].goods[index].one;
      var name = that.data.dishes[parentIndex].goods[index].name;
      var id = that.data.dishes[parentIndex].goods[index].id;
      var icon = that.data.dishes[parentIndex].goods[index].img;
      var store = that.data.store
      var obj = { money: money, num: num, kc: kc, id: id, mark: mark, name: name, index: index, parentIndex: parentIndex, icon: icon, store: store, box_fee: box_fee, allmoney: (money * num).toFixed(2) };
      var carArray1 = that.data.carArray.filter(item => item.mark != mark)
      carArray1.splice(index, 0, obj)
      // console.log(this.data.dishes[parentIndex].goods)
      that.setData({
        shop_cart: carArray1,
        carArray: carArray1,
        dishes: that.data.dishes
      })
      that.calTotalPrice();
      that.setData({
        payDesc: that.payDesc()
      })
      console.log(that.data.dishes)
    }
  },
  decreaseCart: function (e) {
    console.log('你点击了减号')
    var that = this;
    console.log(this.data)
    var index = e.currentTarget.dataset.itemIndex;
    var parentIndex = e.currentTarget.dataset.parentindex;
    console.log(index, parentIndex)
    console.log(parentIndex, that.data.dishes[parentIndex].goods[index].id)
    // 请求此菜品是否多规格
    app.util.request({
      'url': 'entry/wxapp/DishesGg',
      'cachetime': '0',
      data: { dishes_id: that.data.dishes[parentIndex].goods[index].id },
      success: function (res) {
        console.log(res)
        if (res.data.length != 0) {
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: '多规格商品只能在购物车删除哦',
          })
        }
        else {
          that.data.dishes[parentIndex].goods[index].one--;
          var mark = 'a' + index + 'b' + parentIndex
          if (that.data.types == 2) {
            var money = that.data.dishes[parentIndex].goods[index].wm_money;
          } else {
            var money = that.data.dishes[parentIndex].goods[index].money;
          }
          var box_fee = that.data.dishes[parentIndex].goods[index].box_fee;
          console.log("餐盒费是：" + box_fee)
          var kc = Number(that.data.dishes[parentIndex].goods[index].num);
          var num = that.data.dishes[parentIndex].goods[index].one;
          var name = that.data.dishes[parentIndex].goods[index].name;
          var id = that.data.dishes[parentIndex].goods[index].id;
          var icon = that.data.dishes[parentIndex].goods[index].img;
          var store = that.data.store
          var obj = { money: money, num: num, kc: kc, id: id, mark: mark, name: name, index: index, parentIndex: parentIndex, icon: icon, store: store, box_fee: box_fee, allmoney: (money * num).toFixed(2) };
          var carArray1 = that.data.carArray.filter(item => item.mark != mark)
          carArray1.splice(index, 0, obj)
          // console.log(this.data.dishes[parentIndex].goods)
          that.setData({
            shop_cart: carArray1,
            carArray: carArray1,
            dishes: that.data.dishes
          })
          wx.setStorageSync('carArr', carArray1);
          that.calTotalPrice();
          that.setData({
            payDesc: that.payDesc()
          })
          console.log(that.data.dishes)
        }
      },
    })
  },
  //
  xzggClick: function (e) {
    this.setData({
      xzggindex: e.currentTarget.id
    });
  },
  //
  xhl: function () {
    var index = this.data.zindex;
    var parentIndex = this.data.findex;
    console.log(this.data.zindex, this.data.findex)
    console.log(this.data.dishes)
    this.data.dishes[parentIndex].goods[index].one++;
    this.data.dishes[parentIndex].goods[index].gg[this.data.xzggindex].num++;
    var mark = 'a' + index + 'b' + parentIndex + 'c' + this.data.gg[this.data.xzggindex].id
    var ggindex = this.data.xzggindex
    if (this.data.types == 2) {
      var money = this.data.gg[this.data.xzggindex].cost;
    } else {
      var money = this.data.gg[this.data.xzggindex].cost;
    }
    var box_fee = this.data.dishes[parentIndex].goods[index].box_fee;
    console.log("餐盒费是：" + box_fee)
    var kc = Number(this.data.dishes[parentIndex].goods[index].num);
    var num = this.data.dishes[parentIndex].goods[index].gg[this.data.xzggindex].num;
    var name = this.data.ggbt + this.data.gg[this.data.xzggindex].name;
    var id = this.data.dishes[parentIndex].goods[index].id;
    // console.log(id)
    var icon = this.data.dishes[parentIndex].goods[index].img;
    var store = this.data.store
    var obj = { ggindex: ggindex, money: money, num: num, kc: kc, id: id, mark: mark, name: name, index: index, parentIndex: parentIndex, icon: icon, store: store, box_fee: box_fee, allmoney: (money * num).toFixed(2) };
    var carArray1 = this.data.carArray.filter(item => item.mark != mark)
    carArray1.splice(index, 0, obj)
    console.log(carArray1)
    this.setData({
      shop_cart: carArray1,
      carArray: carArray1,
      dishes: this.data.dishes
    })
    this.calTotalPrice();
    this.setData({
      payDesc: this.payDesc()
    })
    this.setData({
      showModal: false,
      xzggindex: 0
    })
  },
  //——————————————点击加号——————添加到购物车
  addCart: function (e) {
    console.log(this.data)
    var that = this;
    var index = e.currentTarget.dataset.itemIndex;
    var parentIndex = e.currentTarget.dataset.parentindex;
    this.setData({
      zindex: index,
      findex: parentIndex
    })
    console.log(parentIndex, that.data.dishes[parentIndex].goods[index].id)
    // 请求此菜品是否多规格
    app.util.request({
      'url': 'entry/wxapp/DishesGg',
      'cachetime': '0',
      data: { dishes_id: that.data.dishes[parentIndex].goods[index].id },
      success: function (res) {
        console.log(res)
        //是多规格
        if (res.data.length != 0) {
          //如果是多规格且第一次点
          if (that.data.dishes[parentIndex].goods[index].gg == null) {
            that.setData({
              showModal: true,
              gg: res.data,
              ggbt: that.data.dishes[parentIndex].goods[index].name
            })
            that.data.dishes[parentIndex].goods[index].gg = res.data
            that.setData({
              dishes: that.data.dishes
            })
            console.log(that.data.dishes)
          }
          //如果是多规格且不是第一次点
          else {
            that.setData({
              showModal: true,
              gg: res.data,
              ggbt: that.data.dishes[parentIndex].goods[index].name
            })
            console.log(that.data.dishes)
          }
        }//不是多规格
        else {
          console.log(that.data.dishes[parentIndex].goods[index].one);
          that.data.dishes[parentIndex].goods[index].one++;
          var mark = 'a' + index + 'b' + parentIndex
          if (that.data.types == 2) {
            var money = that.data.dishes[parentIndex].goods[index].wm_money;
          } else {
            var money = that.data.dishes[parentIndex].goods[index].money;
          }
          var box_fee = that.data.dishes[parentIndex].goods[index].box_fee;
          console.log("餐盒费是：" + box_fee)
          var kc = Number(that.data.dishes[parentIndex].goods[index].num);
          var num = that.data.dishes[parentIndex].goods[index].one;
          var name = that.data.dishes[parentIndex].goods[index].name;
          var id = that.data.dishes[parentIndex].goods[index].id;
          // console.log(id)
          var icon = that.data.dishes[parentIndex].goods[index].img;
          var store = that.data.store
          var obj = { money: money, num: num, kc: kc, id: id, mark: mark, name: name, index: index, parentIndex: parentIndex, icon: icon, store: store, box_fee: box_fee, allmoney: (money * num).toFixed(2) };
          var carArray1 = that.data.carArray.filter(item => item.mark != mark)
          carArray1.splice(index, 0, obj)
          console.log(carArray1)
          that.setData({
            shop_cart: carArray1,
            carArray: carArray1,
            dishes: that.data.dishes
          })
          wx.setStorageSync("carArr", carArray1);
          console.log(that.data.dishes)
          that.calTotalPrice();
          that.setData({
            payDesc: that.payDesc()
          })
        }
      },
    })
  },

  //计算总价
  calTotalPrice: function () {
    // console.log(this.data)
    var carArray = this.data.carArray;
    var totalPrice = 0;
    var totalbox = 0;
    var totalCount = 0;
    for (var i = 0; i < carArray.length; i++) {
      if (this.data.types == 2) {
        totalPrice += carArray[i].money * carArray[i].num + carArray[i].box_fee * carArray[i].num;
        totalCount += carArray[i].num;
        totalbox += carArray[i].box_fee * carArray[i].num;
      } else {
        totalPrice += carArray[i].money * carArray[i].num;
        totalCount += carArray[i].num;
      }
      console.log(totalPrice)

    }
    // console.log(carArray)
    this.setData({
      shop_cart: carArray,
      totalPrice: totalPrice.toFixed(2),
      totalCount: totalCount,
      totalbox: totalbox
    });
  },
  //差几元起送
  payDesc() {
    console.log(this.data)
    var totalPrice = parseFloat(this.data.totalPrice)
    var start_at = parseFloat(this.data.start_at)
    if (this.data.types == 2) {
      if (this.data.totalPrice == 0) {
        return '￥' + this.data.start_at + '元起送';
      } else if (this.data.totalPrice <= 0) {
        return '￥' + this.data.start_at + '元起送';
      } else if (totalPrice < start_at) {
        console.log(this.data.totalPrice)
        let diff = start_at - totalPrice;
        return '还差' + diff.toFixed(2) + '元起送';
        console.log(start_at - totalPrice)
      } else {
        console.log(totalPrice)
        return '去结算';
      }
    } else {
      if (this.data.totalPrice >= 0) {
        return '去下单';
      }
    }

  },
  clear: function (e) {
    var that = this
    that.setData({
      shop_cart: [],
      carArray: [],
      carArray1: [],
      changeHidden: true
    })
    that.calTotalPrice();
    that.reload()
  },
  // 点击预览图片
  clickImage: function (e) {
    var that = this
    // 第一种放在scroll-view标签里面，苹果不显示
    // var id = e.currentTarget.id
    // var dishes = this.data.dishes
    // for (var i = 0, len = dishes.length; i < len; ++i) {
    //   // console.log(dishes[i].goods)
    //   for (var j = 0; j < dishes[i].goods.length; j++) {
    //     // console.log(dishes[i].goods[j])
    //     if (dishes[i].goods[j].id == id) {
    //       dishes[i].goods[j].open = !dishes[i].goods[j].open
    //     } else {
    //       dishes[i].goods[j].open = false
    //     }
    //     that.setData({
    //       dishes: dishes,
    //       id: e.currentTarget.id
    //     });
    //   }
    // }
    console.log(e)
    console.log(that.data)
    // 第二种，跳转页面,请求菜品详情的接口
    var url = that.data.url
    var urls = []
    var index = e.target.dataset.id
    console.log(index)
    var img = []
    // console.log(index)
    for (var n = 0; n < that.data.dishes.length; n++) {
      // console.log(that.data.dishes[n].goods)
      for (var m = 0; m < that.data.dishes[n].goods.length; m++) {
        console.log(that.data.dishes[n].goods[m].id)
        if (that.data.dishes[n].goods[m].id == index) {
          img.splice(index, 0, that.data.dishes[n].goods[m].img)
          // console.log(that.data)
          var goodm = that.data.dishes[n].goods[m]
          app.util.request({
            'url': 'entry/wxapp/DishesInfo',
            'cachetime': '0',
            data: { id: goodm.id },
            success: function (res) {
              console.log(res.data)
              wx: wx.navigateTo({
                // url: '../dishinfo/dishinfo?id=' + goodm.id + '&types=' + that.data.types,
                url: '/zh_dianc/pages/fooddetail/fooddetail?id=' + goodm.id
              })
            },
          })
        }
      }
    }

    // 第二种，微信自带的预览图片
    // urls.splice(index, 0,url + img);
    // wx.previewImage({
    //   // current: url + '/attachment/',
    //   urls: urls// 需要预览的图片http链接列表
    // })
  },
  bomb: function (e) {
    var that = this
    var id = e.currentTarget.id
    var dishes = this.data.dishes
    for (var i = 0, len = dishes.length; i < len; ++i) {
      // console.log(dishes[i].goods)
      var goods = dishes[i].goods;
      for (var j = 0; j < goods.length; j++) {
        // console.log(goods[j])
        if (goods[j].id == id) {
          goods[j].open = !goods[j].open
        } else {
          goods[j].open = false
        }
      }
    }
    this.setData({
      dishes: dishes,
      id: e.currentTarget.id
    });
  },
  jcgwc: function (arr) {
    var a = 0;
    for (var i in arr) {
      if (arr[i].num != 0) {
        a++
      }
    }
    return a;
  },
  jsmj: function (num, arr) {
    var index;
    for (let i = 0; i < arr.length; i++) {
      if (Number(num) >= Number(arr[i].full)) {
        index = i;
        break;
      }
    }
    return index
  },
  //結算
  pay(e) {
    if (this.data.types == 2) {
      var pay = this.data.shop_cart;
      console.log(this.data.shop_cart)
      console.log(this.jcgwc(pay))
      console.log(this.data)
      wx.setStorageSync("store", this.data.store)
      wx.setStorageSync("order", this.data.shop_cart)
      if (pay == null || pay.length == 0) {
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: '请选择菜品',
        })
        return
      }
      if (this.jcgwc(pay) == 0) {
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: '请选择菜品',
        })
        return
      }
      if (parseFloat(this.data.totalPrice) < parseFloat(this.data.start_at)) {
        return;
      }
      var resultType = "success";
      var that = this;
      that.toPay(this.data.shop_cart);

      // wx.navigateTo({
      //   url: '../pay/pay?types=' + this.data.types
      // })

    }
  },
  navInfo: function (e) {
    wx.switchTab({
      url: '../info/info',
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  // ————————————————————底部弹框——————————————————————
  change: function (e) {
    console.log('1111')
    this.setData({ changeHidden: true })
  },
  toastChange: function (e) {
    this.setData({ toastHidden: true })
  },
  change1: function (e) {
    console.log('1111')
    this.setData({ changeHidden: false })
  },
  ktpay: function () {
    wx.showModal({
      title: '提示',
      content: '此桌已开台不能点菜',
    })
  },
  //自定义算距离方法
  distance: function (f, t, cbk) {
    // 调用距离接口
    var distance;
    qqmapsdk.calculateDistance({
      mode: 'driving',
      from: {
        latitude: f.lat,
        longitude: f.lng
      },
      to: [{
        latitude: t.lat,
        longitude: t.lng
      }],
      success: function (res) {
        console.log(res);
        if (res.status == 0) {
          distance = Math.round(res.result.elements[0].distance)
          cbk(distance)
        }
      },
      fail: function (res) {
        console.log(res);
        if (res.status == 373) {
          distance = 15000;
          cbk(distance)
        }
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },
  toPay: function (order) {
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: "K3HBZ-4QRC3-2RC3U-YOLYP-GJFA2-JNFST"
    });
    console.log(qqmapsdk);

    // return false;
    var ye = Number(this.data.wallet), money = Number(this.data.money);
    var is_yue = 2;
    console.log('是否余额', is_yue)
    var that = this
    // 配送费
    var freight = that.data.freight
    if (that.data.dnzt) {
      var dnzt = 1, sdsj = that.data.date + '日' + that.data.time + '分';
      freight = 0;
    }
    else {
      var dnzt = 2;
      if (that.data.sdindex == 0) {
        var sdsj = '尽快送达,预计' + that.data.sd_time + '内送达'
      }
      else {
        var sdsj = that.data.date + '日' + that.data.time + '分';
      }
    }
    console.log(that.data, '自提', dnzt, '送达时间', sdsj, '配送费', freight, '总计费用', that.data.money, 'pre', that.data.pre, 'cut', that.data.cut)
    var totalPrice = that.data.totalPrice
    var money = that.data.totalPrice
    if (that.data.xyh_open == 1) {
      if (that.data.new_user == 1) {
        var yhje = that.data.xyh_money
      }
      if (that.data.new_user == 2 && that.data.totalPrice >= that.data.yh) {
        var yhje = that.data.cut + that.data.pre
      }
      if (that.data.new_user == 2 && that.data.totalPrice < that.data.yh) {
        var yhje = that.data.pre
      }
    }
    if (that.data.xyh_open == 2) {
      if (that.data.totalPrice >= that.data.yh) {
        var yhje = that.data.cut + that.data.pre
      }
      if (that.data.totalPrice < that.data.yh) {
        var yhje = that.data.pre
      }
    }
    console.log(yhje)
    var beizhu = that.data.beizhu
    // 菜品信息
    // var order = that.data.order
    console.log(order)
    // 重新构建数组
    var list = []
    order.map(function (item) {
      if (item.num > 0) {
        var obj = {};
        obj.name = item.name;
        obj.img = item.icon;
        obj.num = item.num;
        obj.money = item.money;
        obj.dishes_id = item.id;
        list.push(obj);
      }
    })
    console.log(list)
    console.log('----------------------------------------------下单商品---------------------------------------------------')
    // 满减的优惠条件
    var con = that.data.con
    // 满减的优惠金额
    var cut = that.data.cut
    // 判断用户是否选择了优惠券以及代金券
    if (that.data.coupons_id == null) {
      console.log('用户没有选择优惠券')
      var coupons_id = ''
    } else {
      console.log('用户选择了优惠券')
      // 选择的优惠券id
      var coupons_id = that.data.coupons_id
    }
    if (that.data.vouchers_id == null) {
      console.log('用户没有选择代金券')
      var voucher_id = ''
    } else {
      console.log('用户选择了代金券')
      // 选择的代金券id
      var voucher_id = that.data.vouchers_id
    }
    console.log('代金券id' + voucher_id)
    console.log('优惠券id' + coupons_id)
    // 查看商家是否开启了新用户下单立减
    var xyh_open = that.data.xyh_open
    // 商家设置的下单立减的优惠额度
    var xyh_money = that.data.xyh_money
    // 判断用户是否是新用户
    var new_user = that.data.new_user
    // 获取表单form_id
    var form_id = "the formId is a mock one"
    // user_id
    var user_id = that.data.user_id
    // openid
    var openid = that.data.openid
    // 状态
    var type = 1
    // 名字
    if (that.data.address != null) {
      var name = that.data.address.username
    } else {
      var name = that.data.users.user_name
    }
    // 地址
    if (that.data.address != null) {
      var address = that.data.address.address
    } else {
      var address = that.data.users.user_address
    }
    // 电话
    if (that.data.address != null) {
      var tel = that.data.address.phone
    } else {
      var tel = that.data.users.user_tel
    }
    console.log('用户的名字为' + name)
    console.log('用户的地址为' + address)
    console.log('用户的电话号码为' + tel)

    // 餐盒费
    var box_fee = that.data.totalbox;

    // 商家id
    var seller_id = that.data.seller_id
    console.log(seller_id)
    // 判断支付条件
    if (openid == '') {
      wx: wx.showToast({
        title: 'id为空',
        icon: '',
        image: '',
        duration: 500,
        mask: true,
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    } else {
      if (address == '') {
        // 判断用户是否选择了收货地址
        wx: wx.showToast({
          title: '请先选择地址',
          icon: '',
          image: '',
          duration: 1000,
          mask: true,
          success: function (res) { },
          fail: function (res) { },
          complete: function (res) { },
        })
      } else {
        this.setData({
          zfz: true,
        })
        var shdz = address.replace(" ", "")
        console.log(shdz)
        //区域
        var index = shdz.indexOf('市')
        console.log(shdz.substring(0, index))
        var area = shdz.substring(0, index)
        // 地图
        // 调用接口
        console.log(shdz);
        console.log('---------------------------------------地址------------------------------')
        qqmapsdk.geocoder({
          address: shdz,
          success: function (res) {
            console.log(res);
            console.log('终点:', res.result.location)
            console.log(res.result.location.lat + ',' + res.result.location.lng)
            var shdzlat = res.result.location.lat;
            var shdzlng = res.result.location.lng;
            var end = res.result.location;
            console.log(shdzlat, shdzlng)
            that.distance(that.data.start, end, function (juli) {
              console.log(juli, distance)
              if (distance < juli && dnzt == 2) {
                wx.showModal({
                  title: '提示',
                  content: '超出商家配送距离',
                  showCancel: false,
                })
                that.setData({
                  zfz: false,
                  showModal: false,
                })
              }
              else {
                // 提交订单接口
                if (form_id == '') {
                  wx: wx.showToast({
                    title: '网络不好',
                    icon: '',
                    image: '',
                    duration: 500,
                    mask: true,
                    success: function (res) { },
                    fail: function (res) { },
                    complete: function (res) { },
                  })
                  that.setData({
                    zfz: false,
                  })
                } else {
                  // wx.showLoading({
                  //   title: '加载中',
                  // })
                  console.log(list);
                  console.log('------------------------------------------------下单商品------------------------------')
                  // return false;
                  // 提交订单
                  app.util.request({
                    'url': 'entry/wxapp/AddOrder',
                    'cachetime': '0',
                    data: {
                      type: type, seller_id: seller_id, money: money, user_id: user_id, preferential: yhje, freight: freight, name: name, address: address, tel: tel, box_fee: box_fee, sz: list, coupons_id: coupons_id, voucher_id: voucher_id, note: beizhu,
                      area: area, lat: shdzlat, lng: shdzlng, is_take: dnzt, delivery_time: sdsj, is_yue: is_yue
                    },
                    success: function (res) {
                      // 获取本次下单的id
                      console.log(res)
                      var order_id = res.data
                      console.log('本次的订单id为' + order_id)
                      if (order_id != "下单失败") {
                        //下单成功支付按钮
                        that.setData({
                          zfz: false,
                          showModal: false,
                        })
                        var radiogroup = 'wxzf';
                        if (radiogroup == 'yezf') {
                          console.log('余额支付流程')
                          // 打印机
                          app.util.request({
                            'url': 'entry/wxapp/Print',
                            'cachetime': '0',
                            data: { order_id: order_id },
                            success: function (res) {
                              console.log(res)
                            },
                          })
                          app.util.request({
                            'url': 'entry/wxapp/Print2',
                            'cachetime': '0',
                            data: { order_id: order_id },
                            success: function (res) {
                              console.log(res)

                            },
                          })
                          console.log(that.data.store)
                          if (that.data.store.ps_mode == '1' && !that.data.dnzt) {
                            //达达
                            app.util.request({
                              'url': 'entry/wxapp/dada',
                              'cachetime': '0',
                              data: { area: area, order_id: order_id, lat: shdzlat, lng: shdzlng },
                              success: function (res) {
                                console.log(res)
                              },
                            })
                          }
                          if (that.data.ptxx.is_email == '1') {
                            app.util.request({
                              'url': 'entry/wxapp/email',
                              'cachetime': '0',
                              data: { store_id: seller_id, type: '外卖' },
                              success: function (res) {
                                console.log(res)
                              },
                            })
                          }
                          // 下单改变订单状态
                          app.util.request({
                            'url': 'entry/wxapp/PayOrder',
                            'cachetime': '0',
                            data: { user_id: user_id, order_id: order_id, coupons_id: coupons_id, voucher_id: voucher_id },
                            success: function (res) {
                              console.log(res)
                              wx.showModal({
                                title: '提示',
                                content: '支付成功',
                                showCancel: false,
                              })
                              // 支付成功一秒后返回到首页
                              setTimeout(function () {
                                wx.switchTab({
                                  url: '../list/list'
                                })
                              }, 1000)
                              console.log(form_id)

                              // 下单发送模板消息
                              app.util.request({
                                'url': 'entry/wxapp/message',
                                'cachetime': '0',
                                data: { openid: openid, form_id: form_id, id: order_id },
                                success: function (res) {
                                  console.log(res)

                                },
                              })
                              // 支付完成发送短信给商家
                              app.util.request({
                                'url': 'entry/wxapp/sms',
                                'cachetime': '0',
                                data: { store_id: seller_id },
                                success: function (res) {
                                  console.log(res)

                                },
                              })
                            }
                          })
                        }
                        else {
                          console.log('微信支付流程')
                          // 支付接口
                          app.util.request({
                            'url': 'entry/wxapp/pay',
                            'cachetime': '0',
                            data: { openid: openid, order_id: order_id, money: money },
                            success: function (res) {
                              console.log(res)
                              wx.hideLoading()
                              // 支付
                              wx.requestPayment({
                                'timeStamp': res.data.timeStamp,
                                'nonceStr': res.data.nonceStr,
                                'package': res.data.package,
                                'signType': res.data.signType,
                                'paySign': res.data.paySign,
                                'success': function (res) {
                                  console.log('支付成功', res)
                                  wx.showModal({
                                    title: '提示',
                                    content: '支付成功',
                                    showCancel: false,
                                  })
                                },
                                'complete': function (res) {
                                  console.log('支付完成', res);
                                  if (res.errMsg == 'requestPayment:fail cancel') {
                                    wx.showToast({
                                      title: '取消支付',
                                      icon: 'loading',
                                      duration: 1000
                                    })
                                    setTimeout(function () {
                                      wx.switchTab({
                                        url: '../list/list'
                                      })
                                    }, 1000)
                                  }
                                  if (res.errMsg == 'requestPayment:ok') {
                                    // 打印机
                                    app.util.request({
                                      'url': 'entry/wxapp/Print',
                                      'cachetime': '0',
                                      data: { order_id: order_id },
                                      success: function (res) {
                                        console.log(res)
                                      },
                                    })
                                    app.util.request({
                                      'url': 'entry/wxapp/Print2',
                                      'cachetime': '0',
                                      data: { order_id: order_id },
                                      success: function (res) {
                                        console.log(res)

                                      },
                                    })
                                    console.log(that.data.store)
                                    if (that.data.store.ps_mode == '1' && !that.data.dnzt) {
                                      //达达
                                      app.util.request({
                                        'url': 'entry/wxapp/dada',
                                        'cachetime': '0',
                                        data: { area: area, order_id: order_id, lat: shdzlat, lng: shdzlng },
                                        success: function (res) {
                                          console.log(res)
                                        },
                                      })
                                    }
                                    if (that.data.ptxx.is_email == '1') {
                                      app.util.request({
                                        'url': 'entry/wxapp/email',
                                        'cachetime': '0',
                                        data: { store_id: seller_id, type: '外卖' },
                                        success: function (res) {
                                          console.log(res)
                                        },
                                      })
                                    }
                                    // 下单改变订单状态
                                    app.util.request({
                                      'url': 'entry/wxapp/PayOrder',
                                      'cachetime': '0',
                                      data: { user_id: user_id, order_id: order_id, coupons_id: coupons_id, voucher_id: voucher_id },
                                      success: function (res) {
                                        console.log(res)
                                        // 支付成功一秒后返回到首页
                                        setTimeout(function () {
                                          wx.switchTab({
                                            url: '../list/list'
                                          })
                                        }, 1000)
                                        console.log(form_id)

                                        // 下单发送模板消息
                                        app.util.request({
                                          'url': 'entry/wxapp/message',
                                          'cachetime': '0',
                                          data: { openid: openid, form_id: form_id, id: order_id },
                                          success: function (res) {
                                            console.log(res)
                                          },
                                        })
                                        // 支付完成发送短信给商家
                                        app.util.request({
                                          'url': 'entry/wxapp/sms',
                                          'cachetime': '0',
                                          data: { store_id: seller_id },
                                          success: function (res) {
                                            console.log(res)

                                          },
                                        })
                                      }
                                    })
                                  }
                                }
                              })
                            },
                          })
                        }
                      }
                      else {
                        wx.showToast({
                          title: '下单失败',
                        })
                      }
                    },
                  })
                }
              }
            })
          },
          fail: function (res) {
            console.log(res);
          },
          complete: function (res) {
            console.log(res);
          }
        });
      }
    }
  },
})

